<template>
    <!-- <el-scrollbar ref="scrollMenuRef" class=" bg-color"> -->
    <transition name="el-zoom-in-center">
        <div class="SHZY-preview-main">
            <div class="SHZY-common-page-header">
                <el-page-header @back="goBack" :content="detailId ? (isCopy ? '复制检卡' : '编辑检卡') : '新建检卡'" />
                <div class="options">
                    <el-button type="primary" @click="copy" v-if="!isCopy && detailId">复制</el-button>
                    <el-button type="primary" @click="submit" :loading="btnLoading">保存</el-button>
                    <el-button @click="goBack">取 消</el-button>
                </div>
            </div>
            <!-- <div v-else-if="!isCopy" class="SHZY-common-page-header">
                
                <el-page-header @back="goBack" content="新建检卡" />
                <div class="options">
                    <el-button type="primary" @click="submit" >提交</el-button>
					<el-button @click="goBack">取 消</el-button>
                </div>
            </div> -->

            <transition name="el-zoom-in-top">
                <div>
                    <el-form v-show="unfold" :inline="true" ref="formCheckcard" class="formCheckcard" :model="formCheckcard"
                        label-width="100px">
                        <el-row class="SHZY-common-search-box">
                            <el-col :span="24">

                                <el-form-item label="方案名称" prop="name" required :rules="setRule('请选择方案名称', true)">
                                    <el-input v-model="formCheckcard.name" placeholder="请输入方案名称"></el-input>
                                </el-form-item>
                            </el-col>
                            <!-- <el-col :span="24">
                                <el-form-item label="物料编码" prop="materialCode" required :rules="setRule('请选择物料编码')">
                                    <SHZY-select :list="materialCodeOptions" v-model:bindValue="formCheckcard.materialCode"
                                        label="fullName" value="enCode" placeholder="请输入物料编码" isConcat
                                        concatSymbol=" / "></SHZY-select>
                                </el-form-item>
                            </el-col> -->
                            <el-col :span="24">
                                <el-form-item label="适用业务" required prop="business" :rules="setRule('请选择适用业务')">
                                    <!-- <el-select v-model="formCheckcard.business" placeholder="请选择适用业务">
                                    <el-option v-for="item in businessOptions" :key="item.value" :label="item.fullName"
                                        :value="item.enCode">
                                    </el-option>
                                </el-select> -->
                                    <el-checkbox-group v-model="formCheckcard.business">
                                        <el-checkbox v-for="(item, index) in businessOptions" :label="item.enCode"
                                            :key="index">{{ item.fullName
                                            }}</el-checkbox>
                                    </el-checkbox-group>
                                </el-form-item>
                            </el-col>
                            <!-- <el-col :span="24">
                            <el-form-item label="自定义参数" prop="customParameters">
                                <el-select v-model="formCheckcard.customParameters" multiple placeholder="请选择自定义参数">
                                    <el-option v-for="item in customParameterOptions" :key="item.value"
                                        :label="item.fullName" :value="item.enCode">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col> -->
                            <el-col :span="24">
                                <el-form-item label="备注">
                                    <el-input v-model="formCheckcard.remarks" placeholder="请输入备注" type="textarea" :rows="5"
                                        show-word-limit maxlength="500"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="附件">
                                    <SHZY-UploadFz v-model="fileInfo" showTip :fileSize='5' sizeUnit='MB' :limit="1" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="24">
                                <el-form-item label="有效标志" prop="enabledMark">
                                    <el-switch v-model="formCheckcard.enabledMark" :active-value="1" :inactive-value="0">
                                    </el-switch>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                    <el-divider></el-divider>

                </div>
            </transition>

            <!-- <div class="m-auto mt-10" style="color:#1890FF;">
                <div class="flex-center cursor-pointer" @click="unfold = !unfold">
                    <i :class="unfold ? 'icon-ym icon-ym-btn-collapse' : 'icon-ym icon-ym-btn-expand'"> </i>
                    <div>{{ unfoldText }}</div>
                </div>
            </div> -->

            <!-- <div class="flex-nowrap mt-10 add-sample">
                <el-button type="primary" @click="addSample" style="width:100px;margin:0 0 5px 0px;" v-if="addSampleShow">
                    <i class="el-icon-folder-add"></i>
                    抽样</el-button>
                <div v-else>
                    <el-select v-model="samplingType" placeholder="请选择抽样⽅案" style="margin:0 0 5px 0px;">
                        <el-option v-for="item in sampleOptions" :key="item.value" :label="item.fullName"
                            :value="item.enCode">
                        </el-option>
                    </el-select>
                </div>
                <el-form class="flex-nowrap" v-if="!addSampleShow && samplingType" :inline="true" ref="samplingForm"
                    :model="samplingForm">

                    <el-form-item class="w-100" label="检验水平" prop="gLevel" :rules="setRule('请选择检验水平')"
                        :required="samplingType == 1" v-if="samplingType == 1">
                        <el-select v-model="samplingForm.gLevel">
                            <el-option v-for="item in gLevelOptions" :key="item.value" :label="item.fullName"
                                :value="item.enCode">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item class="w-100" label="国际严格度" prop="gStringency" :rules="setRule('请选择国际严格度')"
                        :required="samplingType == 1" v-if="samplingType == 1">
                        <el-select v-model="samplingForm.gStringency">
                            <el-option v-for="item in gStringencyOptions" :key="item.value" :label="item.fullName"
                                :value="item.enCode">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item class="w-100" label="国际质量限" prop="gQualityLimit" :rules="setRule('请选择国际质量限')"
                        :required="samplingType == 1" v-if="samplingType == 1">
                        <el-select v-model="samplingForm.gQualityLimit">
                            <el-option v-for="item in gQualityLimitOptions" :key="item.value" :label="item.fullName"
                                :value="item.enCode">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="抽样数量" prop="fixedSamplingQty" :rules="setRule('请输入抽样数量')"
                        :required="samplingType == 2" v-if="samplingType == 2">
                        <el-input v-model="samplingForm.fixedSamplingQty"></el-input>
                    </el-form-item>
                    <el-form-item label="比例" prop="fixedRatio" :rules="setRule('请输入比例')" :required="samplingType == 3"
                        v-if="samplingType == 3">
                        <el-input v-model="samplingForm.fixedRatio"
                            @input="samplingForm.fixedRatio = samplingForm.fixedRatio.replace(/^\D*(\d*(?:\.\d{0,99})?).*$/g, '$1')"></el-input>
                    </el-form-item>
                    <el-form-item label="抽检类型" prop="aql" :rules="setRule('请选择抽检类型')" :required="samplingType == 4"
                        v-if="samplingType == 4">
                        <SHZY-select :list="samplingplanOptions" v-model:bindValue="samplingForm.aql" label="name"
                            value="id"></SHZY-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="submitForm('samplingForm')">保存</el-button>
                    </el-form-item>

                </el-form>
            </div> -->
            <el-tabs v-model="activeName" style="padding:0 20px;">

                <el-tab-pane label="抽样方案列表" name="module1">
                    <el-form :inline="true" ref="samplingForm" class="formCheckcard" :model="samplingForm"
                        label-width="100px">
                        <el-row class="SHZY-common-search-box">
                            <el-form-item label="抽样方案">
                                <el-select v-model="samplingType" @change="samplingChange" placeholder="请选择抽样⽅案"
                                    style="margin:0 0 5px 0px;width: 250px;" clearable>
                                    <el-option v-for="item in sampleOptions" :key="item.value" :label="item.fullName"
                                        :value="item.enCode">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="检验水平" prop="gLevel" :rules="setRule('请选择检验水平')"
                                :required="samplingType == 1" v-if="samplingType == 1">
                                <el-select v-model="samplingForm.gLevel">
                                    <el-option v-for="item in gLevelOptions" :key="item.value" :label="item.fullName"
                                        :value="item.enCode">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="国际严格度" prop="gStringency" :rules="setRule('请选择国际严格度')"
                                :required="samplingType == 1" v-if="samplingType == 1">
                                <el-select v-model="samplingForm.gStringency">
                                    <el-option v-for="item in gStringencyOptions" :key="item.value" :label="item.fullName"
                                        :value="item.enCode">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="国际质量限" prop="gQualityLimit" :rules="setRule('请选择国际质量限')"
                                :required="samplingType == 1" v-if="samplingType == 1">
                                <el-select v-model="samplingForm.gQualityLimit">
                                    <el-option v-for="item in gQualityLimitOptions" :key="item.value" :label="item.fullName"
                                        :value="item.enCode">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="抽样数量" prop="fixedSamplingQty" :rules="setRule('请输入抽样数量')"
                                :required="samplingType == 2" v-if="samplingType == 2">
                                <el-input v-model="samplingForm.fixedSamplingQty"></el-input>
                            </el-form-item>
                            <el-form-item label="比例" prop="fixedRatio" :rules="setRule('请输入比例')"
                                :required="samplingType == 3" v-if="samplingType == 3">
                                <el-input v-model="samplingForm.fixedRatio"
                                    @input="samplingForm.fixedRatio = samplingForm.fixedRatio.replace(/^\D*(\d*(?:\.\d{0,99})?).*$/g, '$1')"></el-input>
                            </el-form-item>
                            <el-form-item label="抽检类型" prop="aql" :rules="setRule('请选择抽检类型')" :required="samplingType == 4"
                                v-if="samplingType == 4">
                                <!-- <el-input v-model="samplingForm.aql"></el-input> -->
                                <SHZY-select :list="samplingplanOptions" v-model:bindValue="samplingForm.aql" label="name"
                                    value="id"></SHZY-select>
                            </el-form-item>
                            <el-form-item v-if="samplingType != ''" label=" ">
                                <el-button type="primary" @click="submitForm('samplingForm')">保存</el-button>
                            </el-form-item>
                        </el-row>
                    </el-form>
                    <el-form class="tableForm" ref="tableForm" :model="formData" style="height: 100%;">
                        <el-table ref="table" :data="formData.tableData" size="small" default-expand-all row-key="id" border
                            :tree-props="{ children: 'children' }" :row-class-name="rowClassName" max-height="500px">
                            <el-table-column prop="samplingType" label="抽样方案" fixed="left" width="150">
                                <template slot-scope="scope">
                                    <span v-if="!scope.row.sampleId">
                                        {{ setSamplingType(scope.row) }}
                                    </span>
                                </template>
                            </el-table-column>
                            <el-table-column align="center" label="拖动" width="50">
                                <template slot-scope="scope">
                                    <el-form-item>
                                        <i v-if="scope.row.sampleId" class="drag-handler icon-ym icon-ym-darg"
                                            style="cursor: move;font-size:20px" title='点击拖动' />
                                    </el-form-item>
                                </template>
                            </el-table-column>
                            <el-table-column prop="innspectionName" label="检验项目" width="200">
                                <template slot="header">
                                    <span class="required-sign">*</span>检验项目
                                </template>
                                <template slot-scope="scope">
                                    <el-form-item :prop="`tableData.${setProp(scope.row)}.innspectionName`" required
                                        v-if="scope.row.sampleId" :rules="setRule('请选择检验项目')">
                                        <SHZY-select :list="innspectionNameOptions"
                                            v-model:bindValue="scope.row.innspectionName" label="innspectionName" value="id"
                                            @change=" innspectionChange(scope.row)"></SHZY-select>
                                    </el-form-item>
                                </template>
                            </el-table-column>
                            <el-table-column prop="innspectionEntry" label="检验条⽬" width="200">
                                <template slot="header">
                                    <span class="required-sign">*</span>检验条目
                                </template>
                                <template slot-scope="scope">
                                    <el-form-item :prop="`tableData.${setProp(scope.row)}.innspectionEntry`" required
                                        v-if="scope.row.sampleId" :rules="setRule('请选择检验条目')">
                                        <SHZY-select :list="entryNameOptions" :linkData="scope.row.innspectionName"
                                            linkDataName="ItemsId" v-model:bindValue="scope.row.innspectionEntry"
                                            @change="innspectionChange(scope.row)" label="innspectionName"
                                            value="id"></SHZY-select>
                                    </el-form-item>
                                </template>
                            </el-table-column>
                            <el-table-column prop="innspectionMethod" label="检验⽅法" width="200">
                                <template slot="header">
                                    <span class="required-sign">*</span>检验⽅法
                                </template>
                                <template slot-scope="scope">
                                    <el-form-item :prop="`tableData.${setProp(scope.row)}.innspectionMethod`" required
                                        v-if="scope.row.sampleId" :rules="setRule('请选择检验⽅法')">
                                        <SHZY-select :list="methodOptions" v-model:bindValue="scope.row.innspectionMethod"
                                            v-if="scope.row.sampleId" label="name" value="id"></SHZY-select>
                                    </el-form-item>

                                </template>
                            </el-table-column>
                            <el-table-column prop="type" label="类型" width="120">
                                <template slot="header">
                                    <span class="required-sign">*</span>类型
                                </template>

                                <template slot-scope="scope">
                                    <el-form-item :prop="`tableData.${setProp(scope.row)}.type`" required
                                        v-if="scope.row.sampleId" :rules="setRule('请选择类型')">

                                        <el-select v-model="scope.row.type" size="mini" clearable
                                            @change="typeChange(scope.row)">
                                            <el-option v-for="( item, index ) in  checkCardTypeOptions " :key="index"
                                                :label="item.fullName" :value="item.enCode" />
                                        </el-select>
                                    </el-form-item>

                                    <span v-else>{{ scope.row.type }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column prop="quantitativeStandards" label="定量标准" min-width="450px">
                                <!-- <template slot="header">
                            <span class="required-sign">*</span>定量标准
                        </template> -->
                                <template slot-scope="scope">
                                    <!--  -->
                                    <el-form-item v-if="scope.row.sampleId && scope.row.type == 'ration'"
                                        :prop="`tableData.${setProp(scope.row)}.quantitativeStandards`"
                                        :required="scope.row.type == 'ration'" :rules="setRule('请选择定量标准')">
                                        <el-select v-model="scope.row.quantitativeStandards" @change="setTableColumnWidth"
                                            style="width: 100px;" size="mini" clearable>
                                            <el-option v-for="( item, index ) in  quantitativeStandardsOptions "
                                                :key="index" :label="item.fullName" :value="item.enCode" />
                                        </el-select>
                                    </el-form-item>

                                    <template v-if="scope.row.type == 'ration'">
                                        <div v-if="scope.row.quantitativeStandards == 1" ref="sectionFormRef"
                                            class="table-form">
                                            <el-row>
                                                <el-col :span="8">
                                                    <el-form-item style="margin-left: 5px;">
                                                        <el-input v-model="scope.row.standardValue" placeholder="标准值"
                                                            @input="scope.row.standardValue = scope.row.standardValue.replace(/^\D*(\d*(?:\.\d{0,99})?).*$/g, '$1');
                                                            scope.row.accuracy = scope.row.standardValue.split('.')[1] && scope.row.standardValue.split('.')[1].length"
                                                            size="mini"></el-input>
                                                    </el-form-item>

                                                </el-col>
                                                <el-col :span="8">
                                                    <el-form-item style="margin-left: 5px;">
                                                        <el-input v-model="scope.row.minimumValue" placeholder="最小值"
                                                            @blur=inputBlur(scope.row)
                                                            @input="scope.row.minimumValue = scope.row.minimumValue.replace(/^\D*(\d*(?:\.\d{0,99})?).*$/g, '$1')"
                                                            size="mini"></el-input>
                                                    </el-form-item>
                                                </el-col>
                                                <el-col :span="8">
                                                    <el-form-item style="margin-left: 5px;">
                                                        <el-input v-model="scope.row.maximumValue" placeholder="最大值"
                                                            @blur=inputBlur(scope.row)
                                                            @input="scope.row.maximumValue = scope.row.maximumValue.replace(/^\D*(\d*(?:\.\d{0,99})?).*$/g, '$1')"
                                                            size="mini"></el-input></el-form-item>
                                                </el-col>
                                            </el-row>
                                        </div>
                                        <div class="table-form" v-else-if="scope.row.quantitativeStandards == 7">
                                            <el-row>
                                                <el-col :span="8">
                                                    <el-form-item style="margin-left: 5px;">
                                                        <el-input v-model="scope.row.standardValue" placeholder="标准值"
                                                            @input="scope.row.standardValue = scope.row.standardValue.replace(/^\D*(\d*(?:\.\d{0,99})?).*$/g, '$1');
                                                            scope.row.accuracy = scope.row.standardValue.split('.')[1].length"
                                                            size="mini"></el-input></el-form-item>
                                                </el-col>
                                                <el-col :span="8">
                                                    <el-form-item style="margin-left: 5px;">
                                                        <el-input v-model="scope.row.upperDeviation" placeholder="上偏差"
                                                            @blur=inputBlur(scope.row)
                                                            @input="scope.row.upperDeviation = scope.row.upperDeviation.replace(/^\D*(\d*(?:\.\d{0,99})?).*$/g, '$1')"
                                                            size="mini" v-if="scope.row.sampleId"></el-input>
                                                    </el-form-item>
                                                </el-col>
                                                <el-col :span="8">
                                                    <el-form-item style="margin-left: 5px;">
                                                        <el-input v-model="scope.row.lowerDeviation" placeholder="下偏差"
                                                            @blur=inputBlur(scope.row)
                                                            @input="scope.row.lowerDeviation = scope.row.lowerDeviation.replace(/^\D*(\d*(?:\.\d{0,99})?).*$/g, '$1')"
                                                            size="mini" v-if="scope.row.sampleId"></el-input>
                                                    </el-form-item>
                                                </el-col>
                                            </el-row>
                                        </div>
                                        <div class="table-form"
                                            v-else-if="scope.row.sampleId && scope.row.quantitativeStandards">
                                            <el-form-item style="margin-left: 5px;">
                                                <el-input v-model="scope.row.standardValue" placeholder="标准值" @input="scope.row.standardValue = scope.row.standardValue.replace(/^\D*(\d*(?:\.\d{0,99})?).*$/g, '$1');
                                                scope.row.accuracy = scope.row.standardValue.split('.')[1].length"
                                                    size="mini"></el-input>
                                            </el-form-item>
                                        </div>
                                    </template>
                                </template>
                            </el-table-column>
                            <el-table-column prop="accuracy" label="精度">
                                <template slot-scope="scope">
                                    <el-input v-model.number="scope.row.accuracy" size="mini"
                                        v-if="scope.row.sampleId && scope.row.type == 'ration'"></el-input>
                                    <!-- <span v-if="scope.row.sampleId">{{ scope.row.accuracy }}</span> -->
                                </template>
                            </el-table-column>
                            <el-table-column prop="unit" label="单位" width="120">
                                <template slot-scope="scope">
                                    <el-form-item v-if="scope.row.sampleId && scope.row.type == 'ration'">
                                        <el-select v-model='scope.row.unit' placeholder='请选择' clearable filterable>
                                            <el-option v-for="(item, index) in unitOptions" :key="index"
                                                :label="item.fullName" :value="item.fullName"></el-option>
                                        </el-select>
                                    </el-form-item>
                                    <!-- <el-input v-model="scope.row.unit" size="mini" v-if="scope.row.sampleId"></el-input> -->
                                    <!-- <span v-if="scope.row.sampleId">{{ scope.row.unit }}</span> -->
                                </template>
                            </el-table-column>
                            <el-table-column prop="remarks" label="" width="50">
                                <template slot-scope="scope">
                                    <el-button type="text" @click="openMoreDialog(scope.row)"
                                        v-if="scope.row.sampleId">更多</el-button>
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" fixed="right" width="150">
                                <template slot-scope="scope">
                                    <el-button type="text" @click="addRow(scope)"
                                        :disabled="!scope.row.sampleId">新增</el-button>
                                    <el-button type="text" @click="copyRow(scope.row)"
                                        :disabled="!scope.row.sampleId">复制</el-button>
                                    <el-button type="text"
                                        @click="deleteRow(scope.row.id, scope.row.sampleId, scope.row.insertFlag)"
                                        class='SHZY-table-delBtn'>删除</el-button>
                                </template>
                            </el-table-column>
                            <!-- <el-table-column prop="" fixed="right" label=" " width="100">
                        <template slot-scope="scope">
                            <div class="flex-nowrap justify-around w-full font-size-16">
                                <i class="el-icon-circle-plus cursor-pointer" v-if="scope.row.sampleId"
                                    @click="addRow(scope)"></i>
                                <i class="el-icon-document-add cursor-pointer" v-if="scope.row.sampleId"
                                    @click="copyRow(scope.row)"></i>
                                <i class="el-icon-delete cursor-pointer"
                                    @click="deleteRow(scope.row.id, scope.row.sampleId, scope.row.insertFlag)"></i>
                            </div>
                        </template>
                    </el-table-column> -->
                        </el-table>
                    </el-form>
                </el-tab-pane>
                <el-tab-pane label="物料列表" name="module2">
                    <el-table :data="formData.materialList" size='mini'>
                        <el-table-column type="index" width="50" label="序号" align="center" />
                        <el-table-column prop="materialCode" width="200" label="物料编号"></el-table-column>
                        <el-table-column prop="materialDes" label="物料"></el-table-column>
                        <el-table-column prop="enabledMark" label="有效标志">
                            <template slot-scope="scope">
                                <el-tag :type="scope.row.enabledMark == 1 ? 'success' : 'danger'" disable-transitions>
                                    {{ scope.row.enabledMark == 1 ? '正常' : '停用' }} </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" fixed="right" width="150">
                            <template slot-scope="scope">
                                <el-button type="text" @click="addMaterial(scope.row, scope.$index)">编辑</el-button>
                                <el-button type="text" @click="deleteMaterial(scope.row.id, scope.$index)"
                                    class='SHZY-table-delBtn'>删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <div class="table-actions" @click="addMaterial()">
                        <el-button type="text" icon="el-icon-plus">添加物料</el-button>
                    </div>
                </el-tab-pane>
            </el-tabs>



            <SHZY-Dialog dialogTitle="选择检卡复制" appenToBody :visible.sync="copyVisible" @copyDetail="copyDetail"
                emitEvent="copyDetail" width="50%">
                <div class="p-5">
                    <el-table v-loading="listLoading" style="height: 400px;" ref="copyTable" :data="list"
                        @sort-change='sortChange' @selection-change='handleSelectionChange' custom-column>
                        <el-table-column type="selection" width="55">
                        </el-table-column>
                        <el-table-column label="物料编码" prop="materialCode" align="left" sortable='custom'>
                        </el-table-column>
                        <el-table-column label="适用业务" prop="business" align="left" sortable='custom'>
                            <template slot-scope="{row}">
                                {{ setCheckBoxVal(row.business, businessOptions) }}
                            </template>
                        </el-table-column>
                        <!-- <el-table-column label="自定义参数" prop="customParameters" align="left" sortable='custom'>
                        <template slot-scope="{row}">
                            {{ setCheckBoxVal(row.customParameters, customParameterOptions) }}
                        </template>
                    </el-table-column> -->
                        <el-table-column label="备注" prop="remarks" align="left" sortable='custom'>
                        </el-table-column>
                    </el-table>
                    <pagination :total="total" :page.sync="listQuery.currentPage" :limit.sync="listQuery.pageSize"
                        @pagination="getCopyList" />
                </div>

            </SHZY-Dialog>

            <SHZY-Dialog :dialogTitle="dialogTitle" appenToBody :visible.sync="moreDialogShow" emitEvent="saveMore"
                @saveMore="saveMore">
                <div class="p-1">
                    <el-form ref="moreForm" :model="moreForm" label-width="100px">
                        <!-- <el-form-item label="自定义参数">
                        <el-select v-model="moreForm.customParameters" multiple placeholder="请选择自定义参数">
                            <el-option v-for=" item  in  customParameterOptions " :key="item.value" :label="item.fullName"
                                :value="item.enCode">
                            </el-option>
                        </el-select>
                    </el-form-item> -->
                        <el-form-item label="限定逻辑">
                            <el-radio-group v-model='moreForm.qualifyingLogic' size='small'>
                                <el-radio-button v-for="(item, index) in options1" :key="index" :label="item.id">{{
                                    item.fullName }}</el-radio-button>
                            </el-radio-group>
                            <!-- <el-input type="textarea" placeholder="请输入限定逻辑" v-model="moreForm.qualifyingLogic" maxlength="50"
                            show-word-limit :rows="3"></el-input> -->
                        </el-form-item>
                        <el-form-item label="限定供应商">
                            <SHZY-select :list="supplierOptions" v-model:bindValue="moreForm.supplier" label="name"
                                value="code" concatSymbol=" / " isConcat
                                :disabled="!moreForm.qualifyingLogic"></SHZY-select>
                        </el-form-item>
                        <el-form-item label="限定客户">
                            <SHZY-select :list="customerOptions" v-model:bindValue="moreForm.customer" label="name"
                                value="code" concatSymbol=" / " isConcat
                                :disabled="!moreForm.qualifyingLogic"></SHZY-select>

                        </el-form-item>
                        <el-form-item label="限定业务类型">

                            <!-- <el-select v-model="moreForm.businessType" placeholder="请输入限定业务类型">
                            <el-option v-for="item in limitBusinessTypeOptions" :key="item.value" :label="item.fullName"
                                :value="item.enCode">
                            </el-option>
                        </el-select> -->
                            <el-checkbox-group v-model="moreForm.businessType">
                                <el-checkbox v-for="(item, index) in limitBusinessTypeOptions" :label="item.enCode"
                                    :key="index" :disabled="!moreForm.qualifyingLogic">{{
                                        item.fullName
                                    }}</el-checkbox>
                            </el-checkbox-group>
                        </el-form-item>
                        <el-form-item label="参考">
                            <el-radio-group v-model='moreForm.referTo' size='small'>
                                <el-radio-button v-for="(item, index) in options1" :key="index" :label="item.id">{{
                                    item.fullName }}</el-radio-button>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="破坏性">
                            <el-radio-group v-model='moreForm.destructiveness' size='small'>
                                <el-radio-button v-for="(item, index) in options1" :key="index" :label="item.id">{{
                                    item.fullName }}</el-radio-button>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="备注">
                            <el-input type="textarea" placeholder="备注" v-model="moreForm.remarks" show-word-limit
                                maxlength="500" :rows="3"></el-input>
                        </el-form-item>
                        <el-form-item label="附件">
                            <SHZY-UploadFz v-model="moreForm.fileInfo" showTip :fileSize='5' sizeUnit='MB' :limit="1" />
                        </el-form-item>
                        <el-form-item label="有效标志">
                            <el-switch v-model="moreForm.enabledMark" :active-value="1" :inactive-value="0">
                            </el-switch>
                        </el-form-item>
                        <!-- <el-form-item label="公式">
                        <el-input type="textarea" placeholder="请输入公式" v-model="moreForm.formula" maxlength="50"
                            :rows="3"></el-input>
                    </el-form-item> -->
                    </el-form>
                </div>
            </SHZY-Dialog>

            <SHZY-Dialog :dialogTitle="materailDialogTitle" appenToBody :visible.sync="materailVisible"
                emitEvent="saveMaterail" @saveMaterail="saveMaterail">
                <el-form ref="materailForm" :model="materailForm" label-width="100px">
                    <el-form-item label="物料" prop="materialCode" required :rules="setRule('请选择物料')">
                        <SHZY-select :list="materialCodeOptions" v-model:bindValue="materailForm.materialCode"
                            label="fullName" value="enCode" @change="materialChange" placeholder="请选择物料" isConcat
                            concatSymbol=" / ">
                        </SHZY-select>
                    </el-form-item>
                    <el-form-item label="有效标志" prop="enabledMark">
                        <el-switch v-model="materailForm.enabledMark" :active-value="1" :inactive-value="0">
                        </el-switch>
                    </el-form-item>
                </el-form>
            </SHZY-Dialog>

        </div>
    </transition>
    <!-- </el-scrollbar> -->
</template>

<script>
import { deleteCheckcardsample, deletecCheckcarddetail, getInfo, saveCheckcard, getCheckcardDetail, copy, removeMaterial } from '@/api/q1/basedata/inspectionsCard'
import restAPIEntry from '@/api/q1/basedata/innspectionEntry'
import restAPI from '@/api/q1/basedata/samplingPlan'
import Sortable from 'sortablejs'

// import inspectionsCardTable from './Table'
import SHZYDialog from './diaLog'

import { getCheckcardList } from '@/api/q1/basedata/inspectionsCardList'
import { getMaterialAll } from '@/api/q1/basedata/material'
export default {
    name: 'basedata-innspectionCard',
    components: { SHZYDialog },
    props: {
        detailId: String,
        isCopy: {
            default: false,
            type: Boolean
        },
        detailVisible: {
            default: false,
            type: Boolean
        },
    },
    data() {
        return {
            btnLoading: false,
            formCheckcard: {
                materialCode: null,
                business: [],
                customParameters: [],
                remarks: '',
                id: '',
                enabledMark: 1,
                name: ''
            },
            fileInfo: [],
            businessOptions: [],
            customParameterOptions: [],
            materialCodeOptions: [],
            tableData: [],
            copyVisible: false,
            listLoading: true,
            list: [],
            listQuery: {
                currentPage: 1,
                pageSize: 20,
                sort: "desc",
                sidx: "",
            },
            multipleSelection: [],
            total: 0,
            unfold: true,


            formData: {
                tableData: [],
                materialList: []
            },
            innspectionNameOptions: [],
            entryNameOptions: [],
            linkentryNameOptions: [],
            checkCardTypeOptions: [
                {
                    fullName: '定量',
                    enCode: 'ration'
                },
                {
                    fullName: '定性',
                    enCode: 'qualitative'
                }
            ],
            addSampleShow: true,
            samplingType: '',
            sampleOptions: [],
            quantitativeStandardsOptions: [],
            methodOptions: [],
            gLevelOptions: [],
            gStringencyOptions: [],
            gQualityLimitOptions: [],
            samplingForm: {
                gLevel: '',
                gStringency: '',
                gQualityLimit: '',
                fixedSamplingQty: '',
                fixedRatio: 0,
                aql: ''
            },
            dialogTitle: '',
            moreDialogShow: false,
            moreForm: {
                referTo: false,
                destructiveness: false,
                customParameters: [],
                qualifyingLogic: false,
                supplier: '',
                customer: '',
                businessType: [],
                formula: '',
                fileInfo: [],
                remarks: '',
                enabledMark: 1
            },
            supplierOptions: [],
            customerOptions: [],
            mainId: '',
            columnWidth: 150,
            customParameterOptions: [],
            limitBusinessTypeOptions: [],
            samplingplanOptions: [],
            unitOptions: [],
            treeData: [],
            options1: [{ 'fullName': "关闭", 'id': false }, { 'fullName': "开启", 'id': true }],
            activeName: 'module1',
            materailDialogTitle: '',
            materailVisible: false,
            materailForm: {
                materialCode: undefined,
                materialDes: '',
                enabledMark: 1
            },
            materailTableIndex: null
        }
    },
    created() {
        this.getSamplingplanAll()
        this.getApiMaterialList()
        this.getDictionaryData()
        this.initData()
    },
    computed: {
        setProp() {
            return (row) => {
                const parentIndex = this.formData.tableData.map(item => item.id).indexOf(row.sampleId);
                const index = this.formData.tableData[parentIndex].children.map(item => item.id).indexOf(row.id)
                return `${parentIndex}.children.${index}`
            }
        },
        unfoldText() {
            return this.unfold ? '收起' : '展开'
        },
        setRule() {
            return (name, noNull) => {
                return { required: true, message: name, whitespace: noNull }
            }
        },
        setCheckBoxVal() {
            return (val, options) => {
                let str = ''
                let flag = false
                const vals = val.split(',')
                for (const index in options) {
                    if (vals.includes(options[index].enCode)) {
                        if (flag) str += ','
                        str += options[index].fullName
                        flag = true
                    }

                }
                return str
            }
        },

        getPropPosi() {
            return (row) => {
                let posi = this.findPosi(this.formData.tableData, row, '', '')
                return posi
            }
        },
        findPosi() {
            return (list, row, posi, current) => {
                for (let i = 0; i < list.length; i++) {
                    if (list[i].uuid == row.uuid) {
                        return current + i
                    }
                    if (list[i].children && list[i].children.length) {
                        posi = findPosi(list[i].children || [], row, posi, i + posi + '.children.')
                    }
                }
                return posi
            }
        },
        setSamplingType() {
            return (data) => {
                const code = Number(data.samplingType)
                // let str = this.sampleOptions[index - 1].fullName
                const sample = this.sampleOptions.find(item => {
                    return item.enCode == code
                })
                let str = sample ? sample.fullName : code
                if (data.gLevel) {
                    const gLevel = this.gLevelOptions.find(item => {
                        return item.enCode == data.gLevel
                    })

                    const gStringency = this.gStringencyOptions.find(item => {
                        return item.enCode == data.gStringency
                    })

                    const gQualityLimit = this.gQualityLimitOptions.find(item => {
                        return item.enCode == data.gQualityLimit
                    })
                    str += ' ' + gLevel.fullName + ' ' + gStringency.fullName + ' ' + gQualityLimit.fullName
                } else if (data.fixedSamplingQty) {
                    str += ' ' + data.fixedSamplingQty
                } else if (data.fixedRatio) {
                    str += ' ' + data.fixedRatio + '%'
                } else if (data.aql) {
                    const item = this.samplingplanOptions.find(item => item.id == data.aql)
                    str += ' ' + item.name
                }
                return str
            }

        },
        getMaterailDesc() {
            return code => {
                let str = ''
                this.materialCodeOptions.some(item => {
                    if (item.enCode == code) {
                        str = item.fullName
                        return item.fullName
                    }
                })
                return str
            }
        }
    },
    watch: {

        detailId(val) {
            if (val) {
                this.initData()
            }
        },
        moreDialogShow(val) {
            if (!val) {
                this.moreForm = this.$options.data().moreForm
            }
        },
        "formData.tableData": {
            handler(val) {
                if (val) {
                    this.treeData = this.treeToTile(this.formData.tableData)
                    this.$nextTick(() => {
                        // this.setSort()
                    })
                }
            },
            deep: true
        }
    },
    mounted() {
        this.setSort()
    },
    methods: {
        initData() {
            if (!this.detailId) return;
            getCheckcardDetail(this.detailId).then(res => {
                this.tableData = res.data.children
                for (const item of Object.keys(this.formCheckcard)) {
                    for (const item2 of Object.keys(res.data)) {
                        if (item == item2) {
                            this.formCheckcard[item] = res.data[item2]
                        }
                    }
                }
                this.$set(this.formCheckcard, 'customParameters', this.formCheckcard.customParameters ? this.formCheckcard.customParameters.split(',') : [])
                this.$set(this.formCheckcard, 'business', this.formCheckcard.business.split(','))
                this.fileInfo = res.data.fileInfo
                this.formData.materialList = res.data.materialList
                if (res.data.children) {
                    // 列表复制
                    if (this.isCopy) {
                        this.$set(this.formCheckcard, 'id', '')
                        this.$set(this.formCheckcard, 'materialCode', '')
                        const arr = res.data.children.map(item => {
                            item.id = item.id + 1;
                            item.insertFlag = 'Y'
                            item.children.map(item2 => {
                                item2.fileInfo = item2.fileInfo || [];
                                item2.id = item2.id + 1
                                item2.sampleId = item2.sampleId + 1
                                item2.insertFlag = 'Y'
                                return item2
                            })
                            return item
                        })
                        this.formData.tableData = arr

                    } else {
                        this.mainId = res.data.id;
                        const arr = res.data.children.map(item => {
                            item.children.map(item2 => {
                                item2.fileInfo = item2.fileInfo || []
                                return item2
                            })
                            return item
                        })
                        this.formData.tableData = arr
                    }
                }

            })

        },

        // 删除物料
        deleteMaterial(id, index) {
            this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
                type: 'warning'
            }).then(() => {
                if (id) {
                    removeMaterial(id).then(async res => {
                        this.$message({
                            type: 'success',
                            message: res.msg,
                        })

                        const flag = await this.submit(false)
                        flag && this.initData()
                    })
                } else {
                    this.formData.materialList.splice(index, 1)
                    this.$message({
                        type: 'success',
                        message: '操作成功',
                    })
                }
            }).catch(() => {
            });

        },

        materialChange(e) {
            this.formData.materialList.some(item => {
                if (item.materialCode == e) {
                    this.$set(this.materailForm, 'materialCode', '')
                    this.$message({
                        type: 'error',
                        message: '物料重复',
                    })
                    return;
                }
            })
        },

        // 保存物料
        saveMaterail() {
            this.$refs.materailForm.validate(val => {
                if (val) {
                    this.$set(this.materailForm, 'materialDes', this.getMaterailDesc(this.materailForm.materialCode))
                    if (this.materailForm.id || this.materailTableIndex != null) {
                        this.$set(this.formData.materialList, this.materailTableIndex, this.materailForm)
                    } else {
                        this.formData.materialList.push(this.materailForm);
                    }
                    this.materailVisible = false
                    this.materailTableIndex = null
                }
            })
        },

        samplingChange() {
            this.$refs.samplingForm.resetFields()
            this.samplingForm = this.$options.data().samplingForm
        },

        // 添加物料
        addMaterial(row, index) {
            console.log(row)
            this.materailVisible = true
            this.$nextTick(() => {
                this.materailDialogTitle = row ? '编辑物料' : '新增物料'
                if (row) {
                    this.materailForm = JSON.parse(JSON.stringify(row))
                    this.materailTableIndex = index
                } else {
                    this.materailForm = this.$options.data().materailForm
                }
            })

        },

        // 类型下拉框修改
        typeChange(data) {
            const parentIndex = this.formData.tableData.map(item => item.id).indexOf(data.sampleId)
            const index = this.formData.tableData[parentIndex].children.map(item => item.id).indexOf(data.id)
            this.$set(this.formData.tableData[parentIndex].children[index], 'quantitativeStandards', undefined);
            this.$set(this.formData.tableData[parentIndex].children[index], 'standardValue', undefined);
            this.$set(this.formData.tableData[parentIndex].children[index], 'minimumValue', undefined);
            this.$set(this.formData.tableData[parentIndex].children[index], 'maximumValue', undefined);
            this.$set(this.formData.tableData[parentIndex].children[index], 'upperDeviation', undefined);
            this.$set(this.formData.tableData[parentIndex].children[index], 'lowerDeviation', undefined);
            this.$set(this.formData.tableData[parentIndex].children[index], 'accuracy', undefined);
            this.$set(this.formData.tableData[parentIndex].children[index], 'unit', undefined);
        },

        // 获取检验条目
        GetEntryName(val) {
            const arr = []
            for (const item of this.entryNameOptions) {
                if (item.ItemsId == val) arr.push(item)
            }
            this.linkentryNameOptions = arr
            // restAPIEntry.GetItemsInfo(val).then(res => {
            //     console.log(res.data.list)
            // })
        }
        ,
        // 获取 抽检类型下拉框数据
        getSamplingplanAll() {
            restAPI.getAll().then(res => {
                const arr = res.data.map(item => {
                    return {
                        name: item.name,
                        id: item.id
                    }
                })
                this.samplingplanOptions = arr
            })
        },
        rowClassName({ row }) {
            if (row.sampleId) {
                return row.sampleId + '-' + row.id
            }
        },
        // 定量标准 字段校验
        inputBlur(data) {
            if (data.quantitativeStandards == 1 && data.minimumValue && data.maximumValue) {
                const min = Number(data.minimumValue)
                const max = Number(data.maximumValue)
                if (min > max) {
                    this.$message({
                        type: 'error',
                        message: '最小值不能大于最大值',
                    })
                }
            }
        },

        setTableColumnWidth(val) {
            if (val == 1) {
                this.columnWidth = '550'
            } else if (val == 7) {
                this.columnWidth = '600'
            } else {
                this.columnWidth = '300'
            }
        },
        // 检验项目，检验条目选择后 带出数据
        innspectionChange(rowData) {
            if (rowData.innspectionEntry && rowData.innspectionName) {
                getInfo({
                    innspectionName: rowData.innspectionName,
                    entryName: rowData.innspectionEntry
                }).then(res => {
                    if (res.data) {
                        const parentIndex = this.formData.tableData.map(item => item.id).indexOf(rowData.sampleId);
                        const index = this.formData.tableData[parentIndex].children.map(item => item.id).indexOf(rowData.id);
                        this.$set(this.formData.tableData[parentIndex].children[index], 'innspectionMethod', res.data.method);
                        this.$set(this.formData.tableData[parentIndex].children[index], 'type', res.data.type);
                        this.$set(this.formData.tableData[parentIndex].children[index], 'unit', res.data.unit);
                        this.$set(this.formData.tableData[parentIndex].children[index], 'accuracy', res.data.accuracy);
                    }
                })
            }
        },

        setSort() {
            const _this = this;
            const el = this.$refs.table.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
            Sortable.create(el, {
                sort: true,
                ghostClass: 'sortable-ghost',
                // animation: 150,
                handle: '.drag-handler',// '.el-table__row',
                onEnd: evt => {
                    const sampleId = evt.item.className.split(' ')[1].split('-')[0]
                    const parentIndex = _this.formData.tableData.map(item => item.id).indexOf(sampleId)
                    if (!sampleId || parentIndex < 0) return

                    let { newIndex, oldIndex } = evt
                    newIndex = _this.formData.tableData[parentIndex].children.map(item => item.id).indexOf(this.treeData[newIndex].id)
                    oldIndex = _this.formData.tableData[parentIndex].children.map(item => item.id).indexOf(this.treeData[oldIndex].id)
                    const copyItem1 = _this.formData.tableData[parentIndex].children[oldIndex]
                    const copyItem2 = _this.formData.tableData[parentIndex].children[newIndex]
                    if (copyItem1.sampleId == copyItem2.sampleId) {
                        const targetRow = _this.formData.tableData[parentIndex].children.splice(oldIndex, 1)[0]
                        _this.formData.tableData[parentIndex].children.splice(newIndex, 0, targetRow)

                        this.anewSort(parentIndex)
                    }

                },
                onMove: evt => {
                    const aSampleId = Number(evt.dragged.className.split(' ')[1].split('-')[0])
                    const aId = Number(evt.dragged.className.split(' ')[1].split('-')[1])
                    const bSampleId = Number(evt.related.className.split(' ')[1].split('-')[0])
                    const bId = Number(evt.related.className.split(' ')[1].split('-')[1])
                    if (aSampleId == bSampleId) {
                        return true
                    }
                    return false;
                },
            })

        },


        // 将树数据转化为平铺数据
        treeToTile(treeData, childKey = 'children') {
            const arr = []
            const expanded = data => {
                if (data && data.length > 0) {
                    data.filter(d => d).forEach(e => {
                        arr.push(e)
                        expanded(e[childKey] || [])
                    })
                }
            }
            expanded(treeData)
            return arr
        },

        // 复制检卡行
        copyRow(rowData) {
            const parentIndex = this.formData.tableData.map(item => item.id).indexOf(rowData.sampleId)
            const index = this.formData.tableData[parentIndex].children.map(item => item.id).indexOf(rowData.id)
            this.formData.tableData[parentIndex].children.push({
                ... this.formData.tableData[parentIndex].children[index],
                id: Date.now() + '',
                insertFlag: 'Y'
            })
            this.anewSort(parentIndex)
        },

        //  保存更多
        saveMore() {
            this.$refs.moreForm.validate((valid) => {
                if (valid) {
                    for (const index in this.formData.tableData) {
                        if (this.formData.tableData[index].children) {
                            for (const index2 in this.formData.tableData[index].children) {
                                if (this.formData.tableData[index].children[index2].id == this.currentOperationTableId) {
                                    const obj = {
                                        referTo: this.moreForm.referTo ? 'Y' : 'N',
                                        destructiveness: this.moreForm.destructiveness ? 'Y' : 'N',
                                        customParameters: this.moreForm.customParameters ? this.moreForm.customParameters.join(',') : '',
                                        qualifyingLogic: this.moreForm.qualifyingLogic ? 'Y' : 'N',
                                        businessType: this.moreForm.businessType ? this.moreForm.businessType.join(',') : '',
                                    }
                                    this.$set(this.formData.tableData[index].children, index2, { ...this.formData.tableData[index].children[index2], ...this.moreForm, ...obj })
                                }
                            }
                        }
                    }
                    this.moreForm = this.$options.data().moreForm
                    this.moreDialogShow = false
                }
            })
        },

        // 打开更多弹出框
        openMoreDialog({ id }) {
            this.moreDialogShow = true;
            this.currentOperationTableId = id
            const joinFields = ['customParameters', 'businessType']
            for (const index in this.formData.tableData) {
                if (this.formData.tableData[index].children) {
                    for (const index2 in this.formData.tableData[index].children) {
                        if (this.formData.tableData[index].children[index2].id == this.currentOperationTableId) {
                            Object.keys(this.moreForm).forEach(key => {

                                //  && this.formData.tableData[index].children[index2][key]
                                if (joinFields.includes(key)) {
                                    // this.moreForm[key] = this.formData.tableData[index].children[index2][key].split(',')

                                    this.$set(this.moreForm, key, this.formData.tableData[index].children[index2][key] ? this.formData.tableData[index].children[index2][key].split(',') : [])
                                } else {
                                    // this.moreForm[key] = this.formData.tableData[index].children[index2][key] == undefined ? this.moreForm[key] : this.formData.tableData[index].children[index2][key]
                                    this.$set(this.moreForm, key, this.formData.tableData[index].children[index2][key] == undefined ? this.moreForm[key] : this.formData.tableData[index].children[index2][key])
                                }
                            })
                        }
                    }
                }
            }
            this.$set(this.moreForm, 'referTo', this.moreForm.referTo == 'Y')
            this.$set(this.moreForm, 'destructiveness', this.moreForm.destructiveness == 'Y')
            this.$set(this.moreForm, 'qualifyingLogic', this.moreForm.qualifyingLogic == 'Y')

            this.dialogTitle = '编辑'
        },




        addSample() {
            this.addSampleShow = false
        },


        // 添加表格行
        addRow(data) {
            const sampleId = data.row.sampleId;
            const id = data.row.id
            const parentIndex = this.formData.tableData.map(item => item.id).indexOf(sampleId)
            this.formData.tableData[parentIndex].children.push({
                sampleId: sampleId,
                id: Date.now() + 1 + '',
                innspectionName: null,
                innspectionEntry: null,
                innspectionMethod: null,
                type: undefined,
                quantitativeStandards: undefined,
                standardValue: undefined,
                upperDeviation: undefined,
                lowerDeviation: undefined,
                maximumValue: undefined,
                minimumValue: undefined,
                accuracy: '',
                unit: '',
                remarks: '',
                insertFlag: 'Y',
                fileInfo: [],
                enabledMark: 1,
                referTo: 'N',
                sort: this.formData.tableData[parentIndex].children.length + 1
            })
        },

        anewSort(index) {
            const arr = []
            let i = 0
            for (const item of this.formData.tableData[index].children) {
                arr.push({
                    ...item,
                    sort: i += 1
                })
            }
            this.$set(this.formData.tableData[index], 'children', arr)
            // this.treeData = this.treeToTile(this.formData.tableData)
        },

        // 删除表格行
        deleteRow(id, sampleId, insertFlag) {

            for (const index in this.formData.tableData) {
                if (this.formData.tableData[index].children.length <= 1 && this.formData.tableData[index].id == sampleId) {
                    this.$message({
                        type: 'error',
                        message: '至少保留一行数据',
                    })
                    return;
                }
            }

            if (this.mainId && !insertFlag) {
                this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
                    type: 'warning'
                }).then(() => {
                    if (sampleId) {
                        // 删除抽样方案明细
                        deletecCheckcarddetail(id).then(res => {
                            this.$message({
                                type: 'success',
                                message: res.msg,
                            });
                        })
                    } else {
                        // 删除抽样方案 及 明细
                        deleteCheckcardsample(id).then(res => {
                            this.$message({
                                type: 'success',
                                message: res.msg,
                            });
                        })
                    }
                    for (const index in this.formData.tableData) {
                        if (this.formData.tableData[index].id == id) {
                            this.$delete(this.formData.tableData, index)

                            return;
                        } else
                            if (this.formData.tableData[index].children) {
                                for (const index2 in this.formData.tableData[index].children) {
                                    if (this.formData.tableData[index].children[index2].id == id) {
                                        this.$delete(this.formData.tableData[index].children, index2)
                                        this.anewSort(index)
                                        return;
                                    }
                                }
                            }
                    }
                }).catch(() => {
                });
            } else {
                for (const index in this.formData.tableData) {
                    if (this.formData.tableData[index].id == id) {
                        this.$delete(this.formData.tableData, index)
                        return;
                    } else
                        if (this.formData.tableData[index].children) {
                            for (const index2 in this.formData.tableData[index].children) {
                                if (this.formData.tableData[index].children[index2].id == id) {
                                    this.$delete(this.formData.tableData[index].children, index2)
                                    this.anewSort(index)
                                    return;
                                }
                            }
                        }
                }
            }

        },
        //  表格验证是否填写完整数据
        validateTable() {

            const columnLabel = [
                {
                    label: '检验项目',
                    key: 'innspectionName',
                },
                {
                    label: '检验条⽬',
                    key: 'innspectionEntry',
                },
                {
                    label: '检验⽅法',
                    key: 'innspectionMethod',
                },
                {
                    label: '类型',
                    key: 'type',
                },
                {
                    label: '定量标准',
                    key: 'quantitativeStandards',
                },

            ]
            return new Promise(resolve => {

                this.$refs.tableForm.validate(valid => {
                    if (!valid) {
                        resolve(false)
                    }
                })

                if (this.formData.tableData.length == 0) {
                    this.$message({
                        type: 'error',
                        message: `请添加检验方案`,
                    });
                    resolve(false)
                }
                resolve(true)
            })

        },
        // 抽样表单保存
        submitForm(formName) {
            for (const item of this.formData.tableData) {
                if (item.samplingType == this.samplingType) {
                    this.$message({
                        type: 'error',
                        message: '检卡不能重复维护抽样方案',
                    });
                    return;
                }
            }
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    const nowId = Date.now() + ''
                    this.formData.tableData.push({
                        id: nowId,
                        samplingType: this.samplingType,
                        ...this.samplingForm,
                        enabledMark: 1,
                        insertFlag: 'Y',
                        children: [{
                            id: Date.now() + 1 + '',
                            sampleId: nowId,
                            innspectionName: null,
                            innspectionEntry: null,
                            innspectionMethod: null,
                            type: undefined,
                            quantitativeStandards: undefined,
                            standardValue: undefined,
                            upperDeviation: undefined,
                            lowerDeviation: undefined,
                            maximumValue: undefined,
                            minimumValue: undefined,
                            accuracy: '',
                            unit: '',
                            remarks: '',
                            insertFlag: 'Y',
                            fileInfo: [],
                            enabledMark: 1,
                            sort: 1,
                            referTo: 'N'
                        }]
                    })
                    this.$refs[formName].resetFields();
                    this.addSampleShow = true
                } else {
                    return false;
                }
            });
        },

        copyDetail() {
            if (this.multipleSelection.length == 0) {
                this.$message({
                    type: 'error',
                    message: '请选择一行复制',
                })
                return;
            } else {
                copy({
                    fromId: this.multipleSelection.id,
                    toId: this.detailId
                }).then(res => {
                    this.initData()
                    this.$message({
                        type: 'success',
                        message: '复制成功',
                    })
                    this.copyVisible = false

                })
            }

        },
        sortChange({ column, prop, order }) {
            this.listQuery.sort = order == 'ascending' ? 'asc' : 'desc'
            this.listQuery.sidx = !order ? '' : prop
            this.getCopyList()
        },
        handleSelectionChange(val) {
            this.multipleSelection = val[0]
            if (val.length > 1) {
                this.$refs.copyTable.clearSelection();
                this.$refs.copyTable.toggleRowSelection(val.pop());
            }
        },
        getCopyList() {
            return new Promise(resolve => {
                this.listLoading = true;
                let _query = {
                    ...this.listQuery,
                    ...this.query,
                    menuId: this.menuId,
                };
                let query = {}
                for (let key in _query) {
                    if (Array.isArray(_query[key])) {
                        query[key] = _query[key].join()
                    } else {
                        query[key] = _query[key]
                    }
                }
                getCheckcardList(query).then(res => {
                    this.list = res.data.list
                    this.total = res.data.pagination.total
                    this.listLoading = false
                    resolve(true)
                })
            })

        },

        async copy() {

            const flag = await this.getCopyList()
            if (flag) this.copyVisible = true
        },

        goBack() {
            this.$emit('refresh', true)
        },

        // 获取 物料编码
        getApiMaterialList() {
            getMaterialAll().then(res => {
                const arr = []
                for (const item of res.data.list) {
                    arr.push({
                        fullName: item.name,
                        enCode: item.code,
                        value: item.id
                    })
                }
                this.materialCodeOptions = arr
            })
        },



        getDictionaryData() {
            this.$store.dispatch('base/getDictionaryData', { sort: 'BusinessType' }).then((res) => {
                this.businessOptions = res;
            })
            // this.$store.dispatch('base/getDictionaryData', { sort: 'customParameter' }).then((res) => {
            //     this.customParameterOptions = res
            // })

            // 
            this.$store.dispatch('base/getDictionaryData', { sort: 'sampleType' }).then((res) => {
                this.sampleOptions = res;
            })
            this.$store.dispatch('qms/getInnspectionItemsData').then((res) => {
                this.innspectionNameOptions = res
            })
            this.$store.dispatch('qms/getInnspectionEntryData').then((res) => {
                this.entryNameOptions = res
            })
            this.$store.dispatch('qms/getInnspectionMethodData').then((res) => {
                this.methodOptions = res
            })
            this.$store.dispatch('qms/getInnspectionSupplierData').then((res) => {
                this.supplierOptions = res
            })
            this.$store.dispatch('qms/getInnspectionCustomerData').then((res) => {
                this.customerOptions = res
            })


            this.$store.dispatch('base/getDictionaryData', { sort: 'quantitativeStandards' }).then((res) => {
                this.quantitativeStandardsOptions = res;
            })

            this.$store.dispatch('base/getDictionaryData', { sort: 'gLevel' }).then((res) => {
                this.gLevelOptions = res;
            })

            this.$store.dispatch('base/getDictionaryData', { sort: 'gStringency' }).then((res) => {
                this.gStringencyOptions = res;
            })

            this.$store.dispatch('base/getDictionaryData', { sort: 'gQualityLimit' }).then((res) => {
                this.gQualityLimitOptions = res;
            })

            this.$store.dispatch('base/getDictionaryData', { sort: 'limitBusinessType' }).then((res) => {
                this.limitBusinessTypeOptions = res
            })
            this.$store.dispatch('base/getDictionaryData', { sort: 'InspectionUnit' }).then((res) => {
                this.unitOptions = res
            })

        },
        submit(close = true) {
            return new Promise(resolve => {

                this.$refs.formCheckcard.validate(async (valid) => {
                    if (valid) {
                        const flag = await this.validateTable()
                        if (!flag) return;
                        const data = {
                            ...this.formCheckcard,
                            customParameters: this.formCheckcard.customParameters.join(','),
                            business: this.formCheckcard.business.join(','),
                            fileInfo: this.fileInfo,
                            children: this.formData.tableData,
                            materialList: this.formData.materialList
                        }
                        this.btnLoading = true
                        saveCheckcard(data).then(res => {
                            this.btnLoading = false
                            this.$message({
                                message: res.msg,
                                type: 'success',
                                duration: 1500,
                                onClose: () => {
                                    close && this.$emit('refresh', true)
                                }
                            })
                            // if (!this.detailId) {
                            //     this.$router.push('/q1/basedata/inspectionsCardList')
                            //     this.$emit("update:detailVisible", false)
                            //     this.$emit('refresh', true)
                            // }
                            // if (this.detailVisible && this.detailId) {
                            //     this.$emit("update:detailVisible", false)
                            //     this.$emit('refresh', true)
                            // }
                            resolve(true)

                        }).catch((res) => {
                            this.btnLoading = false;
                        })
                    } else {
                        if (!this.unfold) {
                            this.$message({
                                type: 'error',
                                message: '请填写表单',
                            })
                        }
                    }
                })
            })



        }

    }
}
</script>

<style scoped lang="scss">
.tableForm .el-form-item--small.el-form-item {
    margin: 18px 0px;
}

.required-sign {
    color: red;
}

::v-deep .tree-table {
    .el-table__expanded-cell {
        padding: 0px !important;
    }
}

::v-deep .collapse-title {
    flex: 1 0 90%;
    order: 1;

    .el-collapse-item__header {
        flex: 1 0 auto;
        order: -1;
    }
}

::v-deep .table-form {
    .el-form-item {
        margin-bottom: 0px !important;
    }
}

.p-5 {
    padding: 5px;
}

.tableContainer {
    flex: 1 0 0;
    height: 100%;
    overflow: hidden;
}


::v-deep .w-100 .el-input__inner {
    width: 150px !important;
}

::v-deep .cell {
    display: flex !important;
}


.mt-10 {
    margin-top: 10px;
}

.mt-20 {
    margin-top: 30px;
}

.flex-nowrap {
    display: flex;
    flex-wrap: nowrap;
}

.flex-center {
    display: flex;
    align-items: center;
}

.justify-around {
    justify-content: space-around;
}

.w-full {
    width: 100%;
}

.cursor-pointer {
    cursor: pointer;
}

.font-size-16 {
    font-size: 16px;
}

.add-sample {
    font-size: 13px;
    color: #6FB8FC;
    cursor: pointer;

    span {
        margin-left: 15px;
    }
}

.font-color-blue {
    color: #6FB8FC;
}

.m-auto {
    margin: 0px auto;
}

::v-deep .collapse-title {
    flex: 1 0 90%;
    order: 1;

    .el-collapse-item__header {
        flex: 1 0 auto;
        order: -1;
    }
}



::v-deep .el-dialog .el-dialog__body {
    padding: 25px 20px !important;
}

::v-deep .formCheckcard .el-form-item {
    display: flex !important;
}

.bg-color {
    background-color: white;
    padding: 10px;
}

.flex-center {
    display: flex;
    align-items: center;
    justify-items: center;
}

.mx-4 {
    margin: 0px 4px 0px 4px;
}

.font-bold {
    font-weight: bold;
}

.cursor-pointer {
    cursor: pointer;
}

.mr-5 {
    margin-right: 5px;
}

.version {
    margin: 0px 4px 0px 4px;
    color: #AEABA4;
}

.applicable-area {
    margin: 10px 0px 10px 0px;
    display: flex;
    align-items: center;
    justify-content: space-between;


    .w-1 {
        width: 50%
    }

    .el-checkbox {
        margin-right: 5px;
    }
}

.el-checkbox-group {
    margin-left: 5px;
}

.font-size-13 {
    font-size: 13px;
}

.m-auto {
    margin: 0px auto;
}

.mt-10 {
    margin-top: 10px;
}
</style>